import config from './config.js';
import store from '../store/index.js'; 
export default {
	request(options = {}) {
		return new Promise((resolve, reject) => {
			let url = options.url;
			if (url.indexOf("http://") == -1 && url.indexOf("https://") == -1) {
				options.url = config.domain + url;
			}
		
			let token = uni.getStorageSync("token")
			if(token) {
				options.header.Authorization = uni.getStorageSync("token")
			}
			
			//options.header.Appid = uni.getAccountInfoSync().miniProgram.appId;
			options.complete = (response) => {
				if (response.statusCode == 200) {
					if(response.data.status === 500){
						uni.showToast({title: response.data.msg, icon: "none"});
						reject(response.data)
					}else if(response.data.status === 401) {
						uni.showToast({title: "登陆失效，请重新登陆~", icon: "none"});
						store.commit('setLogin', false)
						store.commit('setUserInfo', '')
						uni.removeStorageSync("token");
						uni.removeStorageSync("userInfo");
						uni.switchTab({url: "/pages/my/my"})
						reject(response.data)
					}else if(response.data.status === 501) {
						uni.showModal({
							title: '提示',
							content: '您的人人豆不足~',
							confirmText:'前往获取',
							cancelText:'取消',
							success (res) {
								if (res.confirm) {
									uni.navigateTo({
										url:"/pages/my/beans"
									})
								}
							}
						})
						reject(response.data)
					}
					
					if(response.header.Authorization) {
						uni.setStorageSync("token", response.header.Authorization)
					}
					resolve(response.data)
				} else {
					uni.showToast({title: '服务器异常，请稍后再试～',icon: "none"});
					reject(response.data)
				}
			}
			uni.request(options)
		})
	},

	post(url, data = {}, header = {}) {
		let options = {
			url: url,
			data: data,
			header: header,
			method: "POST"
		}

		return this.request(options);
	},

	get(url, data = {}, header = {}) {
		let options = {
			url: url,
			data: data,
			header: header
		}

		return this.request(options);
	}
};